﻿using Sustainalytics.Entities.ConnectionStrings;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.DataLayer.ConnectionStrings
{
    public class ConnectionStringsManager : IConnectionStringsManager
    {
        private static IConnectionStringsManager _connectionStringsManager;
        private static IConnectionStringsRepository _connectionStringsRepository;

        private ConnectionStringsManager()
        {
            /* prohibit public instantiation*/
        }

        public static IConnectionStringsManager GetInstance(IConnectionStringsRepository connectionStringsRepository)
        {
            if (_connectionStringsManager != null)
                return _connectionStringsManager;

            if (connectionStringsRepository == null)
                throw new ArgumentException("An instance of type IRepositoryCollection<ConnectionString> is needed in order to create an IConnectionStringsManager!");

            _connectionStringsRepository = connectionStringsRepository;

            InitializeConnectionStrings();

            _connectionStringsManager = new ConnectionStringsManager();

            return _connectionStringsManager;
        }

        private static void InitializeConnectionStrings()
        {
            var lastSuccesfullSyncSession = _connectionStringsRepository.GetLastSuccesfullSyncSession();
            var databaseGroup = _connectionStringsRepository.GetCurrentDatabaseGroup();

            if (lastSuccesfullSyncSession.DatabaseGroup.ToString() != databaseGroup)
                throw new InvalidOperationException("Database group of last sync session is different from database group of connection strings!");
        }

        public IDictionary<ConnectionStringType, string> GetConnectionStrings(List<ConnectionStringType> connectionStringTypeList)
            => connectionStringTypeList.ToDictionary(csType => csType, csType => GetConnectionString(csType));

        public string GetConnectionString(ConnectionStringType connectionStringType)
        {
            var connectionString = _connectionStringsRepository.GetConnectionString(connectionStringType);

            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentException(connectionStringType + " does not have a persistent connection string yet!");

            return connectionString;
        }
    }
}
